#include "../MonitorUI/OriginImageModel.hpp"
#include "../MonitorUI/UILoader.hpp"
#include "../MonitorUI/HandleResultModel.hpp"
#include "../MonitorUI/ConfigLoad.hpp"
#include "../MonitorUI/sdbusClient.hpp"
#include <map>
#include <mutex>
#include <thread>
#include <iostream>

using namespace std::chrono_literals;

UILoader* mainUI=nullptr;
OriginImageModel* oriImage=nullptr;
HandleResultModel* handleImage=nullptr;
sdbusClinet client;

struct  ImgObject
{
  int index;
};

std::map<std::string,ImgObject> ImageMap;

void Handle_NewImage(const std::vector<ImageType>& image)
{
  for(auto & i : image)
  {
    auto ptr=ImageMap.find(i.uuid);
    if(ptr!=ImageMap.end())
      mainUI->ShowOriginImage(i,ptr->second.index);
    else
      std::cout<<"can't find image id "<<i.uuid<<std::endl;
  }
}

void HandleResultModel(const ImageType& image)
{
  mainUI->ShowOriginImage(image,0);
}


std::mutex InitMut;

int main()
{
  ConfigLoad config;
  //dbus服务要提前启动，因为要接收初始化数据
  client.funcMobileConnectChange=[](bool status){
    mainUI->SetMobileConnectStatus(status);
  };
  client.funcRecordChange=[](bool status){
    mainUI->SetRecordStatus(status);
  };
  client.Boot();
  InitMut.lock();
  std::thread UIThread([](){
    auto app=Gtk::Application::create("org.gtkmm.MonitorUI.test");
    UILoader UI;
    mainUI=&UI;
    app->signal_activate().connect([&](){
      app->add_window(*UI.mainWindow);
      UI.mainWindow->set_visible(true);
      InitMut.unlock();
    });
    UI.mainWindow->signal_close_request().connect([]()->bool{
      delete oriImage;
      delete handleImage;
      return true;
    },true);
    app->run();
    mainUI=nullptr;
  });
  InitMut.lock();
  for(std::string i : config.GetCameraIDList())
  {
	  std::cout<<i<<std::endl;
  }
  //创建图像处理模块
  oriImage=new OriginImageModel(config.GetCameraIDList(),config.GetShmSize(),Handle_NewImage);
  handleImage=new class HandleResultModel();

  int counter=1;
  std::list<std::string> cameraID={
	"C1527A0090488",
	"C1527A0090431",
	"C1527A0090503",
	"C1527A0090416",
	"C1527A0090539",
  };
  for(const auto & i : cameraID)
  {
    std::cout<<"Dbus Required "<<i<<std::endl;
    ImageMap.insert({
      i,
      {
        counter
      }
    });
    counter++;
  }
  
  oriImage->Boot();
  handleImage->Boot(HandleResultModel);

  UIThread.join();
  return 0;
}
